package com.wxtf.platform.tools;

import java.sql.Timestamp;
import java.text.*;
import java.util.*;

import org.apache.commons.collections.FastHashMap;

/**
 * <li>Title: FormatUtil.java</li>
 * <li>Project: WorkFrame</li>
 * <li>Package: studio.crescent.common</li>
 * <li>Description: </li>
 * <li>Copyright: Copyright (c) 2010</li>
 * <li>Company: Crescent Studio </li>
 * <li>Created on 2010-11-22 下午04:38:00</li>
 *
 * @author chun_chang
 * @version 1.0
 *
 */
public class FormatUtil {
	private FormatUtil(String dateFormat) {
		_format = new SimpleDateFormat(dateFormat);
	}

	/** 
	 * 描述：getCurentDate YYYY-MM-DD
	 * @return
	 * @CreateOn Jun 28, 2011  3:00:19 PM
	 * @author chun_chang
	 * @throws ParseException 
	 */
	public static String getCurentDate() throws ParseException{
		return safeFormatDate(new Date());
	}
	
	/** 
	 * 描述：getCurentDateTime YYYY-MM-DD HH24:mm:ss
	 * @return
	 * @CreateOn Jun 28, 2011  3:00:39 PM
	 * @author chun_chang
	 */
	public static String getCurentDateTime() throws ParseException{
		return secondFormatDate(new Date());
	}
	/** 
	 * 描述：getCurentDateTime4ms 
	 * @return
	 * @throws ParseException
	 * @CreateOn Nov 20, 2011  9:11:33 AM
	 * @author chun_chang
	 */
	public static String getCurentDateTime4ms() throws ParseException{
		return _format4ms.format(new Date(System.currentTimeMillis()));
	}
	public static String getCurentDateTime4Standms() throws ParseException{
		return _format4Standms.format(new Date(System.currentTimeMillis()));
	}
	
	/**
	 * @param dateString String
	 * @return Date
	 * @throws ParseException
	 */
	public static Date getDate(String dateString) throws ParseException {
		if (dateString == null || "".equals(dateString)) {
			return null;
		}
		return _format.parse(dateString);
	}

	/**
	 * @param date Date
	 * @return String
	 * @throws ParseException
	 */
	public static String getDateAsString(Date date) throws ParseException {
		return _format.format(date);
	}

	/**
	 * @param dateTimeAsString String
	 * @return Timestamp
	 * @throws ParseException
	 */
	public static java.sql.Timestamp getDateTime(String dateTimeAsString) throws ParseException {
		java.util.Date date = _format.parse(dateTimeAsString);
		Timestamp sqlDate = new Timestamp(date.getTime());
		return sqlDate;
	}

	/**
	 * @param date Timestamp
	 * @return String
	 */
	public static String getDateTimeAsString(Timestamp dateTime) {
		if (null != dateTime) {
			return _format.format(dateTime);
		} else {
			return null;
		}
	}

	/**
	 * @param dateFormat String
	 * @return FormatUtil
	 */
	@SuppressWarnings("unchecked")
	public static FormatUtil getInstance(String dateFormat) {
		if ((FormatUtil) _formatters.get(dateFormat) != null) {
			return (FormatUtil) _formatters.get(dateFormat);
		} else {
			FormatUtil formatter = new FormatUtil(dateFormat);
			_formatters.put(dateFormat, formatter);
			return formatter;
		}
	}

	/**
	 * parse Date to String . return null when exception occur
	 * @param dateString
	 * @return Date
	 */
	public static Date safeParseDate(String dateString) {
		if (dateString == null || "".equals(dateString)) {
			return null;
		}
		Date result = null;
		try {
			result = _format.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * parse String to Date . return "" when exception occur
	 * @param date
	 * @return String
	 */
	public static String safeFormatDate(Date date) {
		if (date == null) {
			return "";
		}
		String result = null;
		try {
			result = _format.format(date);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * parse String to Date . return "" when exception occur
	 * @param date
	 * @return String
	 */
	public static String chineseFormatDate(Date date) {
		if (date == null) {
			return "";
		}
		String result = null;
		try {
			result = _formatChinese.format(date);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * parse String to Date . return "" when exception occur
	 * @param date
	 * @return String
	 */
	public static String secondFormatDate(Date date) {
		if (date == null) {
			return "";
		}
		String result = null;
		try {
			result = _formatSimple.format(date);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * parse String to Date . return "" when exception occur
	 * @param date
	 * @return String
	 */
	public static String formatDate(Date date) {
		if (date == null) {
			return "";
		}
		String result = null;
		try {
			result = _format.format(date);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * yyyy-MM-dd
	 * @param date
	 * @return
	 */
	public static String toShortDate(String date) {
		if ("".equals(date)) {
			return "";
		} else {
			return date == null ? "" : date.substring(0, 10);
		}
	}

	/** 
	 * 描述：nextMonth1d 取得下个月第一天
	 * @return
	 * @CreateOn Dec 22, 2011  1:48:57 PM
	 * @author chun_chang
	 * @throws Exception 
	 */
	public static String getFirstDayOfNextMonth() throws Exception {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MONTH, 1);// 减一个月
		calendar.set(Calendar.DATE, 1);// 把日期设置为当月第一天
		return _format.format(calendar.getTime());
	}
	
	/** 
	 * 描述：getNextDay 得到第二天
	 * @param curDay
	 * @return
	 * @CreateOn Dec 23, 2011  8:52:19 AM
	 * @author chun_chang
	 * @throws Exception 
	 */
	public static String getNextDay(String curDay) throws Exception {
		Date curDate = _format1.parse(curDay);
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTime(curDate);
		cal.add(GregorianCalendar.DATE, 1);
		return _format1.format(cal.getTime());
	}
	
	public static String getLastDayOfMonth(String curDay) throws Exception {
		Date curDate = _format1.parse(curDay);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(curDate);
		calendar.set(Calendar.DATE, 1);// 设为当前月的1号
		calendar.add(Calendar.MONTH, 1);// 加一个月，变为下月的1号
		calendar.add(Calendar.DATE, -1);// 减去一天，变为当月最后一天
		return _format1.format(calendar.getTime());
	}
	
	
	/** 
	 * 描述：getTwoDay4ms 获取两个时间的毫秒数
	 * @param d1
	 * @param d2
	 * @return
	 * @throws Exception
	 * @CreateOn Dec 22, 2011  2:34:13 PM
	 * @author chun_chang
	 */
	public static long getTwoDay4ms(String d1, String d2) throws Exception{
		long ms = 0l;
		if("".equals(d1) || null == d1){
			Date mydate = _formatMs.parse(d2);
			ms = (new Date().getTime() - mydate.getTime());
		} else {
			Date date = _formatMs.parse(d1);
			Date mydate = _formatMs.parse(d2);
			ms = (date.getTime() - mydate.getTime());
		}
		ms = Math.abs(ms);
		return ms;
	}
	
	
	private static Calendar calS = Calendar.getInstance();  
	/** 
     * 计算剩余时间 
     * @param startDateStr 
     * @param endDateStr 
     * @return 
     */  
    public static int remainDateToString(String startDateStr, String endDateStr){  
        java.util.Date startDate = null;  
        java.util.Date endDate= null;  
        try {  
            startDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDateStr);  
        } catch (ParseException e) {  
            e.printStackTrace();  
            return 0;  
        }  
        try {  
            endDate = new SimpleDateFormat("yyyy-MM-dd").parse(endDateStr);  
        } catch (ParseException e) {  
            e.printStackTrace();  
            return 0;  
        }  
        calS.setTime(startDate);  
        int startY = calS.get(Calendar.YEAR);  
        int startM = calS.get(Calendar.MONTH);  
        int startD = calS.get(Calendar.DATE);  
        int startDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);  
          
        calS.setTime(endDate);  
        int endY = calS.get(Calendar.YEAR);  
        int endM = calS.get(Calendar.MONTH);  
        //处理2011-01-10到2011-01-10，认为服务为一天  
        int endD = calS.get(Calendar.DATE)+1;  
        int endDayOfMonth = calS.getActualMaximum(Calendar.DAY_OF_MONTH);  
          
        StringBuilder sBuilder = new StringBuilder();  
        if (endDate.compareTo(startDate)<0) {  
            return -1;  
        }  
        int lday = endD-startD;  
        if (lday<0) {  
            endM = endM -1;  
            lday = startDayOfMonth+ lday;  
        }  
        //处理天数问题，如：2011-01-01 到 2013-12-31  2年11个月31天     实际上就是3年  
        if (lday == endDayOfMonth) {  
            endM = endM+1;  
            lday =0;  
        }  
        int mos = (endY - startY)*12 + (endM- startM);  
        int lyear = mos/12;  
        int lmonth = mos%12;  
        if (lyear >0) {  
            sBuilder.append(lyear+"年");  
        }  
        if (lmonth > 0) {  
            sBuilder.append(lmonth+"个月");  
        }  
        if (lday >0 ) {  
            sBuilder.append(lday+"天");  
        }  
        lmonth = (lday>0) ?lmonth+1:lmonth;
        return lyear*12+lmonth;  
    }
      
	
	/**
	 * 
	 * 描述：获取当前日期之前year年的日期，精确到日
	 * @param year 年
	 * @return String
	 * @throws Exception
	 * @CreateOn Sep 21, 2012 9:52:38 AM
	 * @author bai_xin
	 */
	public static String getDateBeforeYear(int year){
		Calendar cal = Calendar.getInstance();
		int _year = cal.get(Calendar.YEAR);
	    _year = _year - year;
		cal.set(Calendar.YEAR, _year);
	    return _format.format(cal.getTime());
	}
	
	
	
	
	
	
	
	public static SimpleDateFormat _format1 = new SimpleDateFormat("yyyyMMdd");
	private static SimpleDateFormat _formatMs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
	
	public static SimpleDateFormat _format = new SimpleDateFormat("yyyy-MM-dd");
	private static SimpleDateFormat _formatChinese = new SimpleDateFormat("yyyy年MM月dd日");
	private static SimpleDateFormat _formatSimple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static SimpleDateFormat _format4ms = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private static SimpleDateFormat _format4Standms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
	@SuppressWarnings("unchecked")
	private static HashMap _formatters = new FastHashMap();
}
